<script setup lang="ts">
import { ref, watch } from 'vue';
import BarChart from './bar-chart.vue';
defineOptions({
  name: 'BarChartComponent'
});
const viewType = defineModel<string>('viewType', { default: '图表' });
// 定义接收的数据props
const props = defineProps<{
  data?: {
    xAxisData: string[];
    seriesData: Array<{
      name: string;
      data: number[];
    }>;
  };
  title?: string;
  tableData?: any[];
}>();

const columns = ref<any[]>([]);

// 生成表格列配置的函数
function generateColumns(data: any[]) {
  if (!data || data.length === 0) {
    columns.value = [];
    return;
  }

  // 获取所有字段名
  const firstRow = data[0];
  const keys = Object.keys(firstRow);

  // 生成列配置
  columns.value = keys.map(key => ({
    title: key.charAt(0).toUpperCase() + key.slice(1), // 首字母大写
    dataIndex: key,
    key,
    width: '25%'
  }));
}

// 监听表格数据变化
watch(
  () => props.tableData,
  newData => {
    if (newData) {
      generateColumns(newData);
    } else {
      columns.value = [];
    }
  },
  { immediate: true } // 立即执行一次
);
</script>

<template>
  <ACard :bordered="false" :head-style="{ padding: '0px 10px' }" :body-style="{ padding: '5px' }" class="card-wrapper">
    <template #title>
      <h3 v-if="props.title" class="chart-title">{{ props.title }}</h3>
    </template>
    <template #extra>
      <ASegmented v-model:value="viewType" :options="['图表', '表格']"></ASegmented>
    </template>
    <BarChart v-if="viewType === '图表'" :data="props.data" />
    <ATable
      v-else
      :pagination="false"
      :columns="columns"
      :data-source="props.tableData"
      :scroll="{ x: 'max-content', y: 400 }"
    ></ATable>
  </ACard>
</template>

<style scoped>
.chart-title {
  margin: 0;
  padding: 0;
  font-size: 16px;
  font-weight: 600;
  color: #1f2937;
}

.dark .chart-title {
  color: #f3f4f6;
}
</style>
